package com.scyshkj.university.wechat.wanxiao;

import com.scyshkj.university.wechat.BeanProvider;
import com.scyshkj.university.wechat.SessionKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by 唐旭 on 2016/11/17.
 */
//@Service
public class WanxiaoOAuthLoginFilter implements Filter {
//    @Autowired
//    private WanxiaoProperties wanxiaoProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SessionKeys.WANXIAO_KEY);
        if (attribute == null) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect(getRedirectUrl());
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private String getRedirectUrl() {
        WanxiaoProperties wanxiaoProperties = BeanProvider.getBean(WanxiaoProperties.class);
        assert wanxiaoProperties != null;

        return wanxiaoProperties.getLoginUrl() + "?" + new WanxiaoLoginParameter(wanxiaoProperties).toUrlString();
    }

    @Override
    public void destroy() {

    }
}
